<?php

require_once('inc/sqlite.php');

define('DIR', '/home/dmdirc/www/');

// We knock a day off because the nightly builds are generated after midnight
// but named after the previous day.
$nightly = strtotime('-1 day', filemtime(DIR . 'nightly/DMDirc_latest.jar'));

$channels = array();
$channels['STABLE'] = array();
$channels['STABLE']['client'] = 20071007; // TODO: Grab this from somewhere
$channels['NIGHTLY'] = array();
$channels['NIGHTLY']['client'] = date('Ymd', $nightly);
$channels['NONE'] = array();

$urls = array();
$urls['STABLE'] = array();
$urls['STABLE']['client'] = 'http://www.dmdirc.com/';
$urls['NIGHTLY'] = array();
$urls['NIGHTLY']['client'] = 'http://www.dmdirc.com/nightly/DMDirc_latest.jar';

if (!isset($_REQUEST['component']) || !isset($_REQUEST['channel'])
	 || !isset($_REQUEST['date'])) {
  die('error Invalid parameters');
}

if (!$db = sqlite_open('admin/data.db', 0777, $sqliteerror)) {
 die('error Database access error');
}

if (!sqlite_table_exists(&$db, 'updatelogs')) {
 sqlite_query($db, 
   'CREATE TABLE updatelogs (
	id INTEGER PRIMARY KEY,
	ip TEXT,
	component TEXT,
	channel TEXT,
	version TEXT,
	time INTEGER
    );');
} 

sqlite_query($db, 
   'INSERT INTO updatelogs (
	ip, component, channel, version, time
    ) VALUES (
	\'' . s($_SERVER['REMOTE_ADDR']) . '\',
	\'' . s($_REQUEST['component']) . '\',
	\'' . s($_REQUEST['channel']) . '\',
	\'' . s($_REQUEST['date']) . '\',
	' . time() . '
    );');

if (!isset($channels[$_REQUEST['channel']])) {
  die('error Invalid channel');
}

$channel = $channels[$_REQUEST['channel']];

if (!isset($channel[$_REQUEST['component']])) {
  die('uptodate Specified component is not available in that channel');
}

if ((int) $channel[$_REQUEST['component']] > (int) $_REQUEST['date']) {
 echo 'outofdate ' . $_REQUEST['component'] . ' ';
 echo $channel[$_REQUEST['component']] . ' ' . $_REQUEST['date'];
 echo ' ' . $urls[$_REQUEST['channel']][$_REQUEST['component']];
} else {
 die('uptodate No newer version of that component in that channel available');
}

?>
